package com.weayer.service;

import com.weayer.constant.CommonStatusEnum;
import com.weayer.constant.TokenConstants;
import com.weayer.dto.ResponseResult;
import com.weayer.dto.TokenResult;
import com.weayer.response.TokenResponse;
import com.weayer.util.JwtUtils;
import com.weayer.util.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @description:  Api服务 - 乘客 -双token service
 * @author: Weayer
 **/
@Service
public class TokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshTokenStr){

        // 解析refreshToken
        TokenResult tokenResult = JwtUtils.checkToken(refreshTokenStr);
        if(tokenResult == null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(), CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        // redis中取出refreshToken校验，生成 tokenKey
        String phone = tokenResult.getPhone();
        String identify = tokenResult.getIdentity();
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identify, TokenConstants.REFRESH_TOKEN_TYPE);
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identify, TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);
        if(StringUtils.isBlank(refreshTokenRedis) || (!refreshTokenStr.trim().equals(refreshTokenRedis.trim()))){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(), CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        // 生成双 token，插入redis中更新
        String refreshToken = JwtUtils.generatorToken(phone, identify, TokenConstants.REFRESH_TOKEN_TYPE);
        String accessToken = JwtUtils.generatorToken(phone, identify, TokenConstants.ACCESS_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 10, TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 60, TimeUnit.SECONDS);
//        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
//        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
